import React, { useRef, useImperativeHandle } from 'react';

import './../index.scss'
import { Input } from 'antd';
import { Ref } from '../atoms';
interface CopyProps {
  text: string;
}
interface InputRefProps {
  copy(): void;
}
/**
 * 复制文本input
 */

// forwardRef转发了父组件的 DOM 元素 而在子组件元素当中实现了copy的方法
const CopyInput = React.forwardRef<InputRefProps, CopyProps>(({ text }, copyInputRef) => {
  const inputRef = useRef<HTMLInputElement>(null);
  // 使用useImperativeHandle API 编写copy的方法
  useImperativeHandle(copyInputRef, () => ({
    copy() {
      const input = inputRef.current;
      if (input && input !== null) {
        input.value = text;
        input.select();
        document.execCommand('copy');
      }
    },
  }));
  //  reactdom.createPotal方法是将 元素丢到了root外层去了
  // return ReactDOM.createPortal(
  //   <input className="book-account-copy-input" readOnly type="text" ref={inputRef} />,
  //   document.body,
  // );
  return (<>
  {/* ant-desigin的ref 不知到怎么拿到 */}
  {/* <Input  className="book-account-copy-input" placeholder="Basic usage" readOnly type="text" ref={inputRef}/> */}
  <Ref className="book-account-copy-input" readOnly type="text" ref={inputRef} ></Ref>

  </>)
});

const Copy: React.FC<CopyProps> = ({ text, children }) => {
  console.log(text);
  console.log(children);
  const inputRef = useRef<InputRefProps>(null);
  const onCopy = () => {
    const input = inputRef.current;
    if (input && input !== null) {
      input.copy();
    }
  };
  return (
    <span onClick={onCopy}>
      <CopyInput ref={inputRef} text={text} />
      {children}
    </span>
  );
};
export default Copy;
